package cn.edu.bupt.mvcdemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.time.LocalTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
public class DemoController {
    private int count =1;

    @GetMapping("/mvc/delay-echo")
    public String handle() throws InterruptedException {
         System.out.println(Thread.currentThread().getName()+" Start");
         Thread.sleep (5000);
         System.out.println(Thread.currentThread().getName()+" End");
         return "delay-echo";
    }

    @GetMapping(value="/mvc/sse")
    public ResponseBodyEmitter handleRequest () {
        System.out.println(Thread.currentThread().getName()+" Start");
        final SseEmitter emitter = new SseEmitter(0L);
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    emitter.send(SseEmitter.event()
                            .id(Long.toString(i))
                            .data(LocalTime.now().toString()));
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                    emitter.completeWithError(e);
                    return;
                }
                System.out.println(Thread.currentThread().getName()+" sending");
            }
            emitter.complete();
        });
        System.out.println(Thread.currentThread().getName()+" end");
        return emitter;
    }
}
